package trading_strategy;

import trading_strategy.events.EventDispatcher;
import trading_strategy.events.EventManager;
import trading_strategy.events.history.TRTHInstrumentReader;
import trading_strategy.instruments.Future;
import trading_strategy.markets.Market;
import trading_strategy.markets.ZeroTransactionCosts;
import trading_strategy.orders.Brokers;
import trading_strategy.orders.InstrumentOrderBroker;
import trading_strategy.orders.simulation.SimulatedExchange;
import trading_strategy.strategies.SignedTradesStrategy;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Semaphore;

/**
 * Created by IntelliJ IDEA.
 * User: gderoujoux
 * Date: 6 mai 2010
 * Time: 09:15:56
 * To change this template use File | Settings | File Templates.
 */
public class TestSignedStrategy {
    public static void main(String[] args) throws ParseException {
        final Market euronext = new Market(1, "EUR", new ZeroTransactionCosts());
        DateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmm");
        Future future = new Future(2, "CAC_FUT", euronext.getId(), sdf.parse("20100618-1100"), 10, 0.5);
        Future[] futures = new Future[]{future};

        double totalPnl = 0;
        double totalCost = 0;
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter("signed_trades.csv"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            EventManager.getInstance().clear();
            SimulatedExchange.clear();
            final TRTHInstrumentReader hr = new TRTHInstrumentReader(future, "history/20100614/CAC_FUT.csv");
            SimulatedExchange exchange = SimulatedExchange.getExchange(future); // Instantiates the simulated exchange
            Brokers.getInstance().registerBroker(future, new InstrumentOrderBroker(exchange)); // The broker
            SignedTradesStrategy start = new SignedTradesStrategy(new Date(), future, writer);
            start.register();
            hr.read();

            System.out.println("Read");
            final Semaphore wait = new Semaphore(0);
            EventManager.getInstance().getDispatcher(EventManager.REPLAY_DISPATCHER).addEvent(new EventDispatcher.TimedRunnable(Long.MAX_VALUE) {
                @Override
                public void run() {
                    wait.release();
                }
            });
            wait.acquire();
            start.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.exit(0);
    }
}